package com.bro.person.admin.exception;

import com.bro.person.admin.common.CommonUrlControl;
import com.bro.person.admin.utils.HttpUtils;
import com.bro.person.base.enums.error.GlobalEnum;
import com.bro.person.base.utils.ResponseBuilderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author swallow
 * Created by swallow on 2018/11/15.<br>
 */
@ControllerAdvice
public class GlobalExceptionHandler{

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defalutErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception ex){
        logger.debug("[GlobalExceptionHandler][defalutErrorHandler] entering request:{},response:{},ex:{}",request, response, ex);
        ModelAndView modelAndView;
        if(HttpUtils.isAjaxRequest(request)){
            if(ex instanceof NoHandlerFoundException){
                modelAndView = ResponseBuilderUtil.buildJsonView(ResponseBuilderUtil.buildErrorJSON(GlobalEnum.BRO_NOT_FOUND_MAPPING_ERROR));
            }else{
                modelAndView = ResponseBuilderUtil.buildJsonView(ResponseBuilderUtil.buildErrorJSON(GlobalEnum.BRO_SYSTEM_ERROR,ex.getMessage()));
            }
        }else{
            RedirectView redirectView = new RedirectView(CommonUrlControl.LOGIN_REDIRECT_URL);
            modelAndView = new ModelAndView(redirectView);
        }
        logger.info("[GlobalExceptionHandler][defalutErrorHandler] desc request:{},response:{},ex:{},modelAndView:{}",request, response, ex, modelAndView);
        return modelAndView;
    }

}
